//
//  CNStickerInputView.m
//  CsdnPlus
//
//  Created by 孟瑞瑞 on 2018/6/6.
//  Copyright © 2018年 CSDN. All rights reserved.
//

#import "CNComposeToolbar.h"
#import <CNBaseViewTool/CNCommentToolbar.h>

@interface CNComposeToolbar ()<PPStickerKeyboardDelegate>

@property (nonatomic, assign, readwrite) CNKeyboardType keyboardType;

@property (nonatomic, strong) PPStickerKeyboard *stickerKeyboard;


@end

@implementation CNComposeToolbar

- (id)init
{
    self = [super init];
    if (self) {
//        UIView *lineView = [[UIView alloc]init];
//        lineView.theme_backgroundColor = bbsSectionLineColorPicker;
//        [self addSubview:lineView];
//        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.right.top.mas_equalTo(0);
//            make.height.mas_equalTo(0.5);
//        }];
        self.contentMode = UIViewContentModeRedraw;
        self.exclusiveTouch = YES;
        self.emojiToggleButton.hidden = NO;
        self.pictureButton.hidden = NO;
        self.scoreButton.hidden = NO;
        self.keyboardType = CNKeyboardTypeSystem;
        
        self.layer.theme_shadowColor = shadowsColorPicker;
        self.layer.shadowOffset = CGSizeMake(0, -0.5);
        self.layer.shadowOpacity = [CNThemesManager isNight]?1:0.15;
        self.layer.shadowRadius = 0;
        
    }
    return self;
}

- (PPButton *)emojiToggleButton
{
    if (!_emojiToggleButton) {
        _emojiToggleButton = [[PPButton alloc] init];
        [_emojiToggleButton theme_setImage:toggleEmojiImage forState:UIControlStateNormal];
        [_emojiToggleButton theme_setImage:toggleKeyboardImage forState:UIControlStateSelected];
        _emojiToggleButton.touchInsets = UIEdgeInsetsMake(-12, -20, -12, -20);
        [_emojiToggleButton addTarget:self action:@selector(toggleKeyboardDidClick:) forControlEvents:UIControlEventTouchUpInside];
        _emojiToggleButton.tag = CNComposeToolbarButtonTypeEmotion;
        [self addSubview:_emojiToggleButton];
        [_emojiToggleButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.pictureButton.mas_left).mas_equalTo(-40);
            make.centerY.mas_equalTo(0);
            make.size.mas_equalTo(CGSizeMake(24, 24));
        }];
    }
    return _emojiToggleButton;
}

- (PPButton *)pictureButton
{
    if (!_pictureButton) {
        _pictureButton = [[PPButton alloc] init];
        [_pictureButton theme_setImage:togglePictureImage forState:UIControlStateNormal];
        [_pictureButton theme_setImage:togglePictureImage forState:UIControlStateHighlighted];
        _pictureButton.touchInsets = UIEdgeInsetsMake(-12, -20, -12, -20);
        [_pictureButton addTarget:self action:@selector(pictureButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        _pictureButton.tag = CNComposeToolbarButtonTypePicture;
        [self addSubview:_pictureButton];
        [_pictureButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-40);
            make.centerY.mas_equalTo(0);
            make.size.mas_equalTo(CGSizeMake(24, 24));
        }];
    }
    return _pictureButton;
}

- (PPButton *)scoreButton
{
    if (!_scoreButton) {
        _scoreButton = [[PPButton alloc] init];
        _scoreButton.theme_backgroundColor = searchPageBGColorPicker;
        _scoreButton.touchInsets = UIEdgeInsetsMake(-12, -20, -12, -20);
        _scoreButton.contentEdgeInsets = UIEdgeInsetsMake(5, 12, 5, 12);
        _scoreButton.titleLabel.font = [UIFont systemFontOfSize:13];
        _scoreButton.layer.borderWidth = 0.5;
        _scoreButton.layer.theme_borderColor = scoreBtnBoardColorPicker;
        _scoreButton.layer.cornerRadius = 13;
        _scoreButton.layer.masksToBounds = YES;
        NSMutableAttributedString *scoreStr = [[NSMutableAttributedString alloc] initWithString:@"给分数"];
        scoreStr.yy_font = [UIFont systemFontOfSize:13]; 
        scoreStr.yy_color = scoreTextColor;
        [scoreStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(0,3)];
        [scoreStr addAttribute:NSForegroundColorAttributeName value:[CNThemesManager isNight] ? cellComNightTitleTextColor :cellComTitleTextColor range:NSMakeRange(0,3)];
        [_scoreButton setAttributedTitle:scoreStr forState:(UIControlStateNormal)];
        [_scoreButton addTarget:self action:@selector(pictureButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        _scoreButton.tag = CNComposeToolbarButtonTypeScore;
        [self addSubview:_scoreButton];
        [_scoreButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.mas_equalTo(0);
        }];
    }
    return _pictureButton;
}

-(void)setScoreStr:(NSMutableAttributedString *)scoreStr
{
    _scoreStr = scoreStr;
    [_scoreButton setAttributedTitle:scoreStr forState:(UIControlStateNormal)];
}

- (PPStickerKeyboard *)stickerKeyboard
{
    if (!_stickerKeyboard) {
        _stickerKeyboard = [[PPStickerKeyboard alloc] init];
        _stickerKeyboard.frame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), [self.stickerKeyboard heightThatFits]);
        _stickerKeyboard.delegate = self;
        [_stickerKeyboard.sendButton setTitle:@"完成" forState:(UIControlStateNormal)];
    }
    return _stickerKeyboard;
}

- (void)toggleKeyboardDidClick:(PPButton *)sender
{
    if ([self.delegate respondsToSelector:@selector(composeToolbar:didClickButton:)]) {
        [self.delegate composeToolbar:self didClickButton:(int)sender.tag];
    }
    CNKeyboardType type;
       if (self.selectedButton == sender) {//如果已经选择过
           type = CNKeyboardTypeSystem;
           self.selectedButton = nil;
       }else{//第一次点击该按钮
       switch (sender.tag) {
           
           case CNComposeToolbarButtonTypeEmotion:
               type = CNKeyboardTypeSticker;
               break;
           default:
               type = CNKeyboardTypeSystem;
               break;
         }
           self.selectedButton = sender;
       }

    [self changeKeyboardTo:type];
}
- (void)setSelectedButton:(nullable PPButton *)selectedButton{
        _selectedButton.selected = !_selectedButton.selected;
        selectedButton.selected = !selectedButton.selected;
       _selectedButton = selectedButton;
}
- (void)pictureButtonDidClick:(UIButton *)sender
{
    if ([self.delegate respondsToSelector:@selector(composeToolbar:didClickButton:)]) {
        [self.delegate composeToolbar:self didClickButton:(int)sender.tag];
    }
}
- (void)changeKeyboardTo:(CNKeyboardType)toType
{
    switch (toType) {
        case CNKeyboardTypeSystem:
            self.textView.inputView = nil;                        // 切换到系统键盘
            [self.textView reloadInputViews];                       // 调用reloadInputViews方法会立刻进行键盘的切换
            break;
        case CNKeyboardTypeSticker:
            self.textView.inputView = self.stickerKeyboard;         // 切换到自定义的表情键盘
            [self.textView reloadInputViews];
            break;
       
        default:
            break;
    }
    
    self.keyboardType = toType;
    [self.textView becomeFirstResponder];
}
//- (void)changeKeyboardTo:(CNKeyboardType)toType
//{
////    if (self.keyboardType == toType) {
////        return;
////    }
//
//    switch (toType) {
//        case CNKeyboardTypeNone:
//            [self.emojiToggleButton theme_setImage:toggleEmojiImage forState:UIControlStateNormal];
//            self.textView.inputView = nil;
//            break;
//        case CNKeyboardTypeSystem:
//            [self.emojiToggleButton theme_setImage:toggleEmojiImage forState:UIControlStateNormal];
//            self.textView.inputView = nil;                          // 切换到系统键盘
//            [self.textView reloadInputViews];                       // 调用reloadInputViews方法会立刻进行键盘的切换
//            break;
//        case CNKeyboardTypeSticker:
//            [self.emojiToggleButton theme_setImage:toggleKeyboardImage forState:UIControlStateNormal];
//            self.textView.inputView = self.stickerKeyboard;         // 切换到自定义的表情键盘
//            [self.textView reloadInputViews];
//            break;
//        default:
//            break;
//    }
//
//    self.keyboardType = toType;
//    [self.textView becomeFirstResponder];
//}
//
#pragma mark - PPStickerKeyboardDelegate

- (void)stickerKeyboard:(PPStickerKeyboard *)stickerKeyboard didClickEmoji:(PPEmoji *)emoji
{
    if (!emoji) {
        return;
    }
    
//    UIImage *emojiImage = [UIImage imageNamed:[@"Sticker.bundle" stringByAppendingPathComponent:emoji.imageName]];
    NSString *imageName = [[[NSBundle bundleForClass:[PPSticker class]] pathForResource:@"Sticker" ofType:@"bundle"] stringByAppendingPathComponent:emoji.imageName];
    UIImage *emojiImage = [UIImage imageWithContentsOfFile:imageName];
    if (!emojiImage) {
        return;
    }
    
    NSRange selectedRange = self.textView.selectedRange;
    NSString *emojiString = [NSString stringWithFormat:@"%@", emoji.emojiDescription];
    NSMutableAttributedString *emojiAttributedString = [[NSMutableAttributedString alloc] initWithString:emojiString];
    [emojiAttributedString pp_setTextBackedString:[PPTextBackedString stringWithString:emojiString] range:emojiAttributedString.pp_rangeOfAll];
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.textView.attributedText];
    [attributedText replaceCharactersInRange:selectedRange withAttributedString:emojiAttributedString];
    self.textView.attributedText = attributedText;
    self.textView.selectedRange = NSMakeRange(selectedRange.location + emojiAttributedString.length, 0);
    
    [self.textView.delegate textViewDidChange:self.textView];
}

- (void)stickerKeyboardDidClickDeleteButton:(PPStickerKeyboard *)stickerKeyboard
{
    NSRange selectedRange = self.textView.selectedRange;
    if (selectedRange.location == 0 && selectedRange.length == 0) {
        return;
    }

    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.textView.attributedText];
    if (selectedRange.length > 0) {
        [attributedText deleteCharactersInRange:selectedRange];
        self.textView.attributedText = attributedText;
        self.textView.selectedRange = NSMakeRange(selectedRange.location, 0);
    } else {
        NSUInteger deleteCharactersCount = 1;
        
        // 下面这段正则匹配是用来匹配文本中的所有系统自带的 emoji 表情，以确认删除按钮将要删除的是否是 emoji。这个正则匹配可以匹配绝大部分的 emoji，得到该 emoji 的正确的 length 值；不过会将某些 combined emoji（如 👨‍👩‍👧‍👦 👨‍👩‍👧‍👦 👨‍👨‍👧‍👧），这种几个 emoji 拼在一起的 combined emoji 则会被匹配成几个个体，删除时会把 combine emoji 拆成个体。瑕不掩瑜，大部分情况下表现正确，至少也不会出现删除 emoji 时崩溃的问题了。
        NSString *emojiPattern1 = @"[\\u2600-\\u27BF\\U0001F300-\\U0001F77F\\U0001F900-\\U0001F9FF]";
        NSString *emojiPattern2 = @"[\\u2600-\\u27BF\\U0001F300-\\U0001F77F\\U0001F900–\\U0001F9FF]\\uFE0F";
        NSString *emojiPattern3 = @"[\\u2600-\\u27BF\\U0001F300-\\U0001F77F\\U0001F900–\\U0001F9FF][\\U0001F3FB-\\U0001F3FF]";
        NSString *emojiPattern4 = @"[\\rU0001F1E6-\\U0001F1FF][\\U0001F1E6-\\U0001F1FF]";
        NSString *pattern = [[NSString alloc] initWithFormat:@"%@|%@|%@|%@", emojiPattern4, emojiPattern3, emojiPattern2, emojiPattern1];
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:kNilOptions error:NULL];
        NSArray<NSTextCheckingResult *> *matches = [regex matchesInString:attributedText.string options:kNilOptions range:NSMakeRange(0, attributedText.string.length)];
        for (NSTextCheckingResult *match in matches) {
            if (match.range.location + match.range.length == selectedRange.location) {
                deleteCharactersCount = match.range.length;
                break;
            }
        }
        
        [attributedText deleteCharactersInRange:NSMakeRange(selectedRange.location - deleteCharactersCount, deleteCharactersCount)];
        self.textView.attributedText = attributedText;
        self.textView.selectedRange = NSMakeRange(selectedRange.location - deleteCharactersCount, 0);
    }

    [self.textView.delegate textViewDidChange:self.textView];
}

- (void)stickerKeyboardDidClickSendButton:(PPStickerKeyboard *)stickerKeyboard
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(composeToolbarDidClickSendButton:)]) {
        [self.delegate composeToolbarDidClickSendButton:self];
    }
}

@end
